package com.AdvancedDemos.Learn网络编程.CS架构.useTCP5改进4实现服务器收到信息时反馈给所有客户端;

import java.io.*;
import java.net.Socket;

//服务器端处理socket的线程
public class ServerSocketThread extends Thread {
    //定义成员变量，将每个线程对象与每个socket绑定
    private Socket thisSocket;

    public ServerSocketThread(Socket thisSocket) {
        this.thisSocket = thisSocket;
    }

    @Override
    public void run() {
        System.out.println("【服务器端】一个新socket开始接收数据！");

        try {
            //接收数据
            //获取输入流
            InputStream inputStream = thisSocket.getInputStream();
            DataInputStream dis = new DataInputStream(inputStream);
            while (true) {
                String data = dis.readUTF();
                System.out.println(data);
                System.out.println(thisSocket.getRemoteSocketAddress());

                // 把这个消息分发给全部客户端进行接收。
                sendMsgToAll(thisSocket.getRemoteSocketAddress() + ":" + data);

                //判断数据是否为结束信号，如果为结束信号，则跳出循环
                if ("#exit#".equals(data)) break;
            }
            //从集合中移除下线的socket
            Server.onLineSockets.remove(thisSocket);
            //关闭资源
            dis.close();
            //socket.close();
            System.out.println("有人下线了：" + thisSocket.getRemoteSocketAddress());
        } catch (Exception e) {
            System.out.println(thisSocket.getRemoteSocketAddress() + "出现了异常，该用户下线了！");
        }
    }

    private void sendMsgToAll(String data) throws IOException {

        for (Socket thisOnlineSocket : Server.onLineSockets) {

            OutputStream os = thisOnlineSocket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(data);
            dos.flush();
        }
    }

}
